// 卡牌数据
const cardTypes = [
    { name: '粑粑', image: 'pictures/粑粑.png' },
    { name: '蛋炒饭', image: 'pictures/蛋炒饭.png' },
    { name: '蛋挞', image: 'pictures/蛋挞.png' },
    { name: '鸡蛋', image: 'pictures/鸡蛋.png' },
    { name: '披萨', image: 'pictures/披萨.png' },
    { name: '石头', image: 'pictures/石头.png' },
    { name: '小楼', image: 'pictures/小楼.png' },
    { name: '白菜', image: 'pictures/白菜.png' },
    { name: '炒菜', image: 'pictures/炒菜.png' }
];

// 游戏规则
const gameRules = {
    '石头': ['小楼'],
    '粑粑': ['披萨', '蛋挞'],
    '鸡蛋': ['蛋炒饭'],
    '白菜': ['炒菜']
};

// 游戏状态
const gameState = {
    playerHealth: 100,
    computerHealth: 100,
    playerCards: [],
    computerCards: [],
    playerPlayedCard: null,
    computerPlayedCard: null,
    deckCards: [],
    gameStarted: false,
    round: 1,
    canPlay: true  // 控制玩家是否可以出牌
};

// DOM 元素
const startGameBtn = document.getElementById('start-game');
const drawCardBtn = document.getElementById('draw-card');
const playerCardsContainer = document.querySelector('.player-cards');
const computerCardsContainer = document.querySelector('.computer-cards');
const playerPlayedCardElement = document.getElementById('player-played-card');
const computerPlayedCardElement = document.getElementById('computer-played-card');
const gameMessageElement = document.getElementById('game-message');
const playerHealthText = document.getElementById('player-health-text');
const computerHealthText = document.getElementById('computer-health-text');
const playerHealthFill = document.querySelector('.player-health');
const computerHealthFill = document.querySelector('.computer-health');

// 初始化游戏
function initGame() {
    // 重置游戏状态
    gameState.playerHealth = 100;
    gameState.computerHealth = 100;
    gameState.playerCards = [];
    gameState.computerCards = [];
    gameState.playerPlayedCard = null;
    gameState.computerPlayedCard = null;
    gameState.deckCards = [];
    gameState.gameStarted = true;
    gameState.round = 1;
    gameState.canPlay = true;
    
    // 清空卡牌容器
    playerCardsContainer.innerHTML = '';
    computerCardsContainer.innerHTML = '';
    playerPlayedCardElement.innerHTML = '';
    computerPlayedCardElement.innerHTML = '';
    
    // 创建牌组（每种卡牌6张）
    for (let i = 0; i < 6; i++) {
        cardTypes.forEach(card => {
            gameState.deckCards.push({...card});
        });
    }
    
    // 洗牌
    shuffleDeck();
    
    // 初始发牌（每人5张）
    for (let i = 0; i < 5; i++) {
        drawCard('player');
        drawCard('computer');
    }
    
    // 更新UI
    updateHealthUI();
    gameMessageElement.innerHTML = '<strong>游戏开始！</strong><br>第1回合：请出牌...';
    startGameBtn.textContent = '重新开始';
    drawCardBtn.disabled = false;
    
    // 显示第一回合提示
    createTurnModal();
}

// 洗牌
function shuffleDeck() {
    for (let i = gameState.deckCards.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [gameState.deckCards[i], gameState.deckCards[j]] = [gameState.deckCards[j], gameState.deckCards[i]];
    }
}

// 抽卡
function drawCard(player) {
    if (gameState.deckCards.length === 0) {
        gameMessageElement.textContent = '牌组已空！';
        return;
    }
    
    const card = gameState.deckCards.pop();
    
    if (player === 'player') {
        gameState.playerCards.push(card);
        renderPlayerCard(card, gameState.playerCards.length - 1);
    } else {
        gameState.computerCards.push(card);
        renderComputerCard(gameState.computerCards.length - 1);
    }
}

// 渲染玩家卡牌
function renderPlayerCard(card, index) {
    const cardElement = document.createElement('div');
    cardElement.className = 'card';
    cardElement.dataset.index = index;
    cardElement.innerHTML = `<img src="${card.image}" alt="${card.name}">`;
    
    cardElement.addEventListener('click', () => {
        if (!gameState.gameStarted) return;  // 修改：只检查游戏是否开始
        playCard('player', index);
    });
    
    playerCardsContainer.appendChild(cardElement);
}

// 渲染电脑卡牌（背面）
function renderComputerCard(index) {
    const cardElement = document.createElement('div');
    cardElement.className = 'card';
    cardElement.dataset.index = index;
    cardElement.innerHTML = `<div style="width:100%;height:100%;background-color:#ddd;"></div>`;
    computerCardsContainer.appendChild(cardElement);
}

// 创建回合交替弹窗
function createTurnModal() {
    // 如果已存在弹窗，先移除
    const existingModal = document.querySelector('.turn-modal');
    if (existingModal) {
        document.body.removeChild(existingModal);
    }
    
    const modal = document.createElement('div');
    modal.className = 'turn-modal';
    
    const modalContent = document.createElement('div');
    modalContent.className = 'turn-modal-content';
    
    const message = document.createElement('h2');
    message.textContent = `第${gameState.round}回合`;
    message.style.fontSize = '24px';
    message.style.color = '#333';
    
    modalContent.appendChild(message);
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (document.body.contains(modal)) {
            document.body.removeChild(modal);
        }
    }, 3000);
}

// 玩家出牌
function playCard(player, index) {
    if (player === 'player' && gameState.canPlay) {
        const card = gameState.playerCards[index];
        
        // 从手牌中移除
        gameState.playerCards.splice(index, 1);
        
        // 更新玩家的手牌显示
        playerCardsContainer.innerHTML = '';
        gameState.playerCards.forEach((card, i) => {
            renderPlayerCard(card, i);
        });
        
        // 显示出的牌
        gameState.playerPlayedCard = card;
        playerPlayedCardElement.innerHTML = `<img src="${card.image}" alt="${card.name}">`;
        
        // 更新消息显示
        if (gameState.round % 2 === 1) {
            // 单数回合，玩家先出
            gameMessageElement.textContent = `第${gameState.round}回合：${card.name}`;
        } else {
            // 偶数回合，电脑已出，玩家回应
            gameMessageElement.textContent += `，${card.name}`;
        }
        
        // 自动抽一张牌
        drawCard('player');
        
        // 更新UI
        updateHealthUI();
        checkGameEnd();
        
        // 如果当前回合是单数回合，轮到电脑
        if (gameState.round % 2 === 1) {
            gameState.canPlay = false;
            setTimeout(computerTurn, 3000);
        } else {
            // 偶数回合，玩家已经出完牌，回合结束
            gameState.round++;
            gameState.canPlay = false;
            setTimeout(() => {
                resetRound();
                setTimeout(computerTurn, 3000);
            }, 3000);
        }
    }
}

// 电脑回合
function computerTurn() {
    if (!gameState.gameStarted) return;
    
    // 根据规则选择牌
    let selectedCardIndex = -1;
    const playerCard = gameState.playerPlayedCard;
    
    if (playerCard && Object.keys(gameRules).includes(playerCard.name)) {
        const validResponses = gameRules[playerCard.name];
        
        // 查找电脑是否有合适的牌
        gameState.computerCards.forEach((card, index) => {
            if (validResponses.includes(card.name) && selectedCardIndex === -1) {
                selectedCardIndex = index;
            }
        });
    }
    
    // 如果没有合适的牌，随机选一张
    if (selectedCardIndex === -1) {
        selectedCardIndex = Math.floor(Math.random() * gameState.computerCards.length);
    }
    
    const card = gameState.computerCards[selectedCardIndex];
    
    // 从手牌中移除
    gameState.computerCards.splice(selectedCardIndex, 1);
    
    // 更新电脑的手牌显示
    computerCardsContainer.innerHTML = '';
    gameState.computerCards.forEach((_, i) => {
        renderComputerCard(i);
    });
    
    // 显示出的牌
    gameState.computerPlayedCard = card;
    computerPlayedCardElement.innerHTML = `<img src="${card.image}" alt="${card.name}">`;
    
    // 更新消息显示
    if (gameState.round % 2 === 1) {
        // 单数回合，电脑回应玩家
        gameMessageElement.textContent += `，${card.name}`;
    } else {
        // 偶数回合，电脑先出
        gameMessageElement.textContent = `第${gameState.round}回合：${card.name}`;
    }
    
    // 自动抽一张牌
    drawCard('computer');
    
    // 判断是否符合规则
    checkRules();
    
    // 更新UI
    updateHealthUI();
    checkGameEnd();
    
    // 回合结束，增加回合数
    gameState.round++;
    
    // 如果下一回合是单数回合，轮到玩家
    if (gameState.round % 2 === 1) {
        setTimeout(() => {
            resetRound();
            gameState.canPlay = true;
            createTurnModal();
        }, 3000);
    } else {
        // 下一回合是偶数回合，允许玩家出牌
        setTimeout(() => {
            resetRound();
            gameState.canPlay = true;
            createTurnModal();
        }, 3000);
    }
}

// 重置回合
function resetRound() {
    playerPlayedCardElement.innerHTML = '';
    computerPlayedCardElement.innerHTML = '';
    gameState.playerPlayedCard = null;
    gameState.computerPlayedCard = null;
    
    // 提示玩家
    gameMessageElement.textContent = `第${gameState.round}回合：请出牌...`;
}

// 检查规则
function checkRules() {
    const playerCard = gameState.playerPlayedCard;
    const computerCard = gameState.computerPlayedCard;
    
    if (!playerCard || !computerCard) return;
    
    // 检查玩家卡牌是否克制电脑卡牌
    if (Object.keys(gameRules).includes(playerCard.name)) {
        const validResponses = gameRules[playerCard.name];
        if (!validResponses.includes(computerCard.name)) {
            // 电脑出错牌，减血
            gameState.computerHealth -= 10;
            gameMessageElement.textContent += `，电脑出错了！电脑失去10点生命值！`;
        }
    }
    
    // 检查电脑卡牌是否克制玩家卡牌
    if (Object.keys(gameRules).includes(computerCard.name)) {
        const validResponses = gameRules[computerCard.name];
        if (!validResponses.includes(playerCard.name)) {
            // 玩家出错牌，减血
            gameState.playerHealth -= 10;
            gameMessageElement.textContent += `，你出错了！你失去10点生命值！`;
        }
    }
}

// 更新血量UI
function updateHealthUI() {
    playerHealthText.textContent = gameState.playerHealth;
    computerHealthText.textContent = gameState.computerHealth;
    
    playerHealthFill.style.width = `${gameState.playerHealth}%`;
    computerHealthFill.style.width = `${gameState.computerHealth}%`;
}

// 检查游戏结束
function checkGameEnd() {
    if (gameState.playerHealth <= 0) {
        gameMessageElement.textContent = '游戏结束！电脑获胜！';
        gameState.gameStarted = false;
        drawCardBtn.disabled = true;
    } else if (gameState.computerHealth <= 0) {
        gameMessageElement.textContent = '游戏结束！你获胜了！';
        gameState.gameStarted = false;
        drawCardBtn.disabled = true;
    }
}

// 事件监听
startGameBtn.addEventListener('click', initGame);
drawCardBtn.addEventListener('click', () => {
    if (!gameState.gameStarted) return;
    drawCard('player');
});

// 初始禁用抽牌按钮
drawCardBtn.disabled = true; 